/**
 * 流式文字显示组件
 * 实现打字机效果的AI回复显示
 */

import React, { useState, useEffect, useRef } from 'react';

interface StreamingTextProps {
    text: string;
    speed?: number; // 打字速度（毫秒）
    isComplete?: boolean;
    className?: string;
    onComplete?: () => void;
}

export const StreamingText: React.FC<StreamingTextProps> = ({
    text,
    speed = 50,
    isComplete = false,
    className = '',
    onComplete
}) => {
    const [displayedText, setDisplayedText] = useState('');
    const [currentIndex, setCurrentIndex] = useState(0);
    const intervalRef = useRef<number | null>(null);

    console.log('🎬 StreamingText 渲染:', { text, displayedText, currentIndex, isComplete });

    // 当文本变化时重置
    useEffect(() => {
        setDisplayedText('');
        setCurrentIndex(0);
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
        }
    }, [text]);

    // 打字机效果
    useEffect(() => {
        if (text && currentIndex < text.length) {
            intervalRef.current = window.setInterval(() => {
                setCurrentIndex(prevIndex => {
                    const nextIndex = prevIndex + 1;
                    if (nextIndex <= text.length) {
                        setDisplayedText(text.slice(0, nextIndex));
                        return nextIndex;
                    } else {
                        if (intervalRef.current) {
                            clearInterval(intervalRef.current);
                        }
                        if (onComplete) {
                            onComplete();
                        }
                        return prevIndex;
                    }
                });
            }, speed);
        }

        return () => {
            if (intervalRef.current) {
                clearInterval(intervalRef.current);
            }
        };
    }, [text, currentIndex, speed, onComplete]);

    // 如果文本为空，直接返回空
    if (!text) {
        return <div className={`streaming-text ${className}`}></div>;
    }

    // 临时简化：直接显示完整文本，不使用打字机效果
    return (
        <div className={`streaming-text ${className}`}>
            <span className="streaming-content">{text}</span>
            {!isComplete && (
                <span className="streaming-cursor">|</span>
            )}
        </div>
    );
};

// AI回复气泡组件
interface AiResponseBubbleProps {
    response: string;
    isComplete: boolean;
    isVisible: boolean;
}

export const AiResponseBubble: React.FC<AiResponseBubbleProps> = ({
    response,
    isComplete,
    isVisible
}) => {
    console.log('🎯 AiResponseBubble 渲染:', { response, isComplete, isVisible });

    if (!isVisible || !response) {
        console.log('❌ AiResponseBubble 不显示:', { isVisible, response });
        return null;
    }

    return (
        <div className="ai-response-bubble">
            <div className="ai-response-content">
                <StreamingText
                    text={response}
                    speed={30}
                    isComplete={isComplete}
                />
            </div>
        </div>
    );
};

// 用户消息气泡组件
interface UserMessageBubbleProps {
    message: string;
    isVisible: boolean;
}

export const UserMessageBubble: React.FC<UserMessageBubbleProps> = ({
    message,
    isVisible
}) => {
    if (!isVisible || !message) {
        return null;
    }

    return (
        <div className="user-message-bubble">
            <div className="user-message-header">
                <span className="user-name">你</span>
                <span className="user-avatar">👤</span>
            </div>
            <div className="user-message-content">
                {message}
            </div>
        </div>
    );
};

// 对话状态组件
interface ConversationStatusProps {
    isListening: boolean;
    isProcessing: boolean;
    isAiThinking: boolean;
    isAiResponding: boolean;
    error: string | null;
}

export const ConversationStatus: React.FC<ConversationStatusProps> = ({
    isListening,
    isProcessing,
    isAiThinking,
    isAiResponding,
    error
}) => {
    if (error) {
        return (
            <div className="conversation-status error">
                <span className="status-icon">❌</span>
                <span className="status-text">错误: {error}</span>
            </div>
        );
    }

    if (isListening) {
        return (
            <div className="conversation-status listening">
                <span className="status-icon">🎤</span>
                <span className="status-text">正在聆听...</span>
            </div>
        );
    }

    if (isProcessing) {
        return (
            <div className="conversation-status processing">
                <span className="status-icon">🔄</span>
                <span className="status-text">处理中...</span>
            </div>
        );
    }

    if (isAiThinking) {
        return (
            <div className="conversation-status thinking">
                <span className="status-icon">🤔</span>
                <span className="status-text">AI思考中...</span>
            </div>
        );
    }

    if (isAiResponding) {
        return (
            <div className="conversation-status responding">
                <span className="status-icon">💬</span>
                <span className="status-text">AI回复中...</span>
            </div>
        );
    }

    return null;
};
